﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using DataMongo;
using HtmlAgilityPack;
using DataMongo.Entities;

using MVCMongo.Services;
using MVCMongo.ViewModel;
using MVCMongo.ViewModel.Submit;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    [Authorize]
    public class SubmitController : Controller
    {
        //
        // GET: /Submit/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetUrlDetail(string url)
        {

           

            var data = new UrlInfoViewModel();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.Method = WebRequestMethods.Http.Get;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());

            String responseString = reader.ReadToEnd();

            response.Close();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(responseString);


           data.Title= (from x in doc.DocumentNode.Descendants()
                            where x.Name.ToLower() == "title"
                            select x.InnerText).FirstOrDefault();

           data.Description = (from x in doc.DocumentNode.Descendants()
                           where x.Name.ToLower() == "meta"
                           && x.Attributes["name"] != null
                           && x.Attributes["name"].Value.ToLower() == "description"
                           select x.Attributes["content"].Value).FirstOrDefault();

            List<String> imgs = (from x in doc.DocumentNode.Descendants()
                                 where x.Name.ToLower() == "img"
                                 select x.Attributes["src"].Value).ToList<String>();
            if (!string.IsNullOrEmpty(data.Title))
            {
                data.Title = HttpUtility.HtmlDecode(data.Title).Trim();
            }
            if (!string.IsNullOrEmpty(data.Description))
            {
                data.Description = HttpUtility.HtmlDecode(data.Description).Trim();
                 
             
            }
            if (imgs.Any())
            {
                data.ImageURl = UtilityService.GetImageUrlFromSite(url);
            }
           
            var connection = new RepositoryBaseMongo("Category");
            var connectionTags = new RepositoryBaseMongo("Tags");
            ViewBag.CategoryList = new SelectList(connection.GetAll<Category>(), "CategoryId", "ShortDescription");
            ViewBag.TagList = new SelectList(connectionTags.GetAll<Tags>(), "TagName", "TagName");
            
            return View("_partialGetUrlInfo", data);
        }

        [HttpPost]
        public ActionResult SubmitUrlPost(UrlInfoViewModel model, List<string> Tag )
        {
            var connection = new RepositoryBaseMongo("FeedPost");

          //checking Id value
            var statusList = connection.GetAll<FeedPost>().ToList();
            int Id = 0;
            if (statusList.Any())
                Id = statusList.Max(x => x.FeedPostId);
            Id += 1;

           
          
            // adding feedpost
                var   feedPost = new FeedPost();
            int index = 0;
            if (Tag.Any())
            {
                foreach (var item   in Tag)
                {
                    if (index == 0)
                    feedPost.Tags = item;
                    else
                    {
                        feedPost.Tags += ", " + item;
                    }
                    index++;
                }
               
            }
            
            feedPost.Title = model.Title;
            feedPost.ShortDescription = model.Description;
            feedPost.PostType = "submit";
            feedPost.PostByUserId = WebSecurity.CurrentUserId;
            feedPost.CategoryId = model.CategoryId;
            feedPost.FeedPostId = Id;
            feedPost.IsActive = true;

                  if (model.ImageURl != null)
                    {
                        var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\";

                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                        var imagepath = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\" + UtilityService.RemoveSpecialCharacters(feedPost.Title) + ".jpg";
                        bool result = UtilityService.DownloadImageFromUrl(model.ImageURl, imagepath);
                        if (result == true)
                        {

                            feedPost.ImageURL1 = UtilityService.RemoveSpecialCharacters(feedPost.Title) + ".jpg";
                        }
                        else
                        {
                            feedPost.ImageURL1 = null;
                        }
                    }
                    else
                    {
                        feedPost.ImageURL1 = null;
                    }
       
            feedPost.PublishDate = DateTime.UtcNow.ToLongDateString();
            connection.InsertOrUpdate(feedPost);
            return View(feedPost);


        }

        public ActionResult SubmitUrl()
        {
            var data = new Url_Info();
            return View(data);
        }

        public ActionResult GetSubmitUrlDetail(string url)
        
        {
          
           
            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
            {
                url = "http://" + url;
            }
           
            var a = new Uri(url);
            var check = a.AbsolutePath.Split('/');
            if (check.Count() > 2)
            {
                ModelState.AddModelError("", "Needed only Valid HostName");
                return View("SubmitUrl");
              
            }
           


            var data = new UrlInfoViewModel();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.Method = WebRequestMethods.Http.Get;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());

            String responseString = reader.ReadToEnd();

            response.Close();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(responseString);


            data.Title = (from x in doc.DocumentNode.Descendants()
                          where x.Name.ToLower() == "title"
                          select x.InnerText).FirstOrDefault();

            data.Description = (from x in doc.DocumentNode.Descendants()
                                where x.Name.ToLower() == "meta"
                                && x.Attributes["name"] != null
                                && x.Attributes["name"].Value.ToLower() == "description"
                                select x.Attributes["content"].Value).FirstOrDefault();

            List<String> imgs = (from x in doc.DocumentNode.Descendants()
                                 where x.Name.ToLower() == "img"
                                 select x.Attributes["src"].Value).ToList<String>();
             var connectionFeed = new RepositoryBaseMongo("FeedPost");
           
            if (!string.IsNullOrEmpty(data.Title))
            {
                data.Title = HttpUtility.HtmlDecode(data.Title).Trim();
            }
            if (!string.IsNullOrEmpty(data.Description))
            {
                data.Description = HttpUtility.HtmlDecode(data.Description).Trim();


            }
            if (imgs.Any())
            {
                data.ImageURl = UtilityService.GetImageUrlFromSite(url);
            }

            var feedist = connectionFeed.GetAll<FeedPost>().Where(x => x.PostType == "submitUrl").Select(x=>x.Title);
            if (feedist.Contains(data.Title))
            {
                ModelState.AddModelError("", "Already Exist");
                return View("SubmitUrl");
            }

            var connection = new RepositoryBaseMongo("Category");
            var connectionTags = new RepositoryBaseMongo("Tags");
            ViewBag.TagList = new SelectList(connectionTags.GetAll<Tags>(), "TagName", "TagName");
            

            return View("_partialGetSubmitUrlInfo", data);
        }

        [HttpPost]
        public ActionResult GetSubmitUrlPost(UrlInfoViewModel model, List<string> Tag )
        {
            var connection = new RepositoryBaseMongo("FeedPost");

            //checking Id value
            var statusList = connection.GetAll<FeedPost>().ToList();
            int Id = 0;
            if (statusList.Any())
                Id = statusList.Max(x => x.FeedPostId);
            Id += 1;


            // adding feedpost
            var feedPost = new FeedPost();
            int index = 0;
            if (Tag.Any())
            {
                foreach (var item in Tag)
                {
                    if (index == 0)
                        feedPost.Tags = item;
                    else
                    {
                        feedPost.Tags += ", " + item;
                    }
                    index++;
                }

            }
            feedPost.Title = model.Title;
            feedPost.ShortDescription = model.Description;
            feedPost.PostType = "submitUrl";
            feedPost.PostByUserId = WebSecurity.CurrentUserId;
            feedPost.CategoryId = model.CategoryId;
            feedPost.FeedPostId = Id;
            feedPost.IsActive = true;

            if (model.ImageURl != null)
            {
                var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\";

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                var imagepath = AppDomain.CurrentDomain.BaseDirectory + "Content\\FeedImages\\" + UtilityService.RemoveSpecialCharacters(feedPost.Title) + ".jpg";
                bool result = UtilityService.DownloadImageFromUrl(model.ImageURl, imagepath);
                if (result == true)
                {

                    feedPost.ImageURL1 = UtilityService.RemoveSpecialCharacters(feedPost.Title) + ".jpg";
                }
                else
                {
                    feedPost.ImageURL1 = null;
                }
            }
            else
            {
                feedPost.ImageURL1 = null;
            }

            feedPost.PublishDate = DateTime.UtcNow.ToLongDateString();
            connection.InsertOrUpdate(feedPost);
            return View("SubmitUrlPost",feedPost);


        }

        //public ActionResult ChectSubmitUrl(string url)
        //{

           

        //}
    }
}
